package com.kid.mvcExt.converter;

import java.sql.Timestamp;
import java.util.regex.Pattern;

import org.springframework.core.convert.converter.Converter;

public class StringToTimestampConverter implements Converter<String, Timestamp> {
	// format like yyyy-MM-dd HH:mm:ss
	private static final Pattern dateStr = Pattern
			.compile("^[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}$");
	private static final Pattern dateLong = Pattern.compile("^[0-9]*$");

	public static void main(String[] args) {
		System.out.println(dateStr.matcher("2012-12-20 15:00:23").matches());
		System.out.println(dateLong.matcher("201223").matches());
	}

	@Override
	public Timestamp convert(String timeStr) {
		Timestamp time = null;
		try {// quick and dirty match
			if (dateStr.matcher(timeStr).matches()) {
				time = Timestamp.valueOf(timeStr);
			} else if (dateLong.matcher(timeStr).matches()) {
				time = new Timestamp(Long.valueOf(timeStr));
			}
		} catch (Throwable t) {
			// TODO log it
			t.printStackTrace();
		}
		// TODO if time is null, log it(means convert failed)
		return time;
	}

}
